<template>
  <div class="order ddingdan kuaishouyewu">
    <el-row>
      <el-col :span="24">
        <div class="grid-content bg-purple-dark">
          <el-tabs v-model="tabNum" @tab-click="handleClick">
            <el-tab-pane
              label="视频业务"
              text-color="#fff"
              name="1"
              class="shipingyewu"
            >
            </el-tab-pane>
            <el-tab-pane label="直播业务" name="2"> </el-tab-pane>
          </el-tabs>
          <div class="xuanxiangkuang" v-if="this.isMobile">
            <el-select v-model="type" placeholder="请选择" @change="selectItem">
              <el-option
                v-for="item in tabNum == '1' ? voideList : streamingList"
                :key="item.bianhao"
                :label="item.bieming"
                :value="item.ziduan"
              >
              </el-option>
            </el-select>
          </div>
        </div>
      </el-col>
    </el-row>
    <!-- 内容部分 -->
    <div class="conter">
      <div class="dianzan" v-for="(item, index) in listData" :key="item.id">
        <div class="dianzanbiaoti">
          {{ item.alias }} {{ item.unit_price }}
          <!-- <img :src="require('@/assets/' + item.tubiao)" />{{ item.bieming }} : -->
          <!-- {{ item.price + item.danwei }} -->
        </div>
        <!-- 内容描述 -->
        <div class="dianzanwenzi">
          {{ item.order_explain }}
          <!-- <p v-for="(items, i) in item.yewushuoming" :key="i">{{ items }}</p> -->
        </div>
        <div class="xiadan">
          <div class="shipinlianjie">
            <el-form :model="item" :rules="rules" :ref="item.id">
              <el-form-item prop="url">
                <el-input
                  :placeholder="item.lianjieleixing | linkType"
                  clearable
                  v-model="item.url"
                ></el-input>
              </el-form-item>
              <el-form-item prop="num" v-if="item.need_text == false">
                <el-input
                  :placeholder="`请输入订单数量(最低下单数${item.min_cnt})${
                    item.gaoshuliang ? ',(最高下单数' + item.max_cnt + ')' : ''
                  }`"
                  clearable
                  oninput="value=value.replace(/[^\d]/g,'')"
                  v-model="item.num"
                  @focus="minmaxNum(item)"
                ></el-input>
              </el-form-item>
              <el-form-item prop="text" v-else class="business_comment">
                <div class="dianzanshuliang">
                  <el-input
                    type="textarea"
                    :autosize="{ minRows: 3, maxRows: 3 }"
                    placeholder="请输入评论内容，每条空一行"
                    v-model="item.text"
                    @input="zhibojiandancifayanshijian"
                    @focus="minmaxText(item, index)"
                  >
                  </el-input>
                  <span class="video">已输入{{ item.textLength }}条</span>
                </div>
              </el-form-item>
              <el-form-item
                prop="time"
                v-if="item.need_time === true"
                class="time"
              >
                <div class="xuanzeshijian">
                  <span>{{
                    item.need_interval === true
                      ? "请选择间隔时间"
                      : "请选择订单时间: "
                  }}</span>
                  <el-select
                    v-model="item.time"
                    placeholder="请选择订单时间"
                    style="width: 50%; margin-left: 6px"
                  >
                    <el-option
                      v-for="items in hunherenqi"
                      :key="items.value"
                      :label="`${items.value}${
                        item.unit_interval == '秒' ? '秒' : '时'
                      }`"
                      :value="items.value"
                    ></el-option>
                  </el-select>
                </div>
              </el-form-item>
              <!-- <el-form-item>
                <div class="dianzanshuliang">
                <span class="video">评论内容</span><span class="video" style="margin-left: 50%;">已输入条</span>
                <el-input type="textarea" :autosize="{ minRows: 3, maxRows: 3}" placeholder="请输入评论内容，每条空一行"></el-input>
                </div>
              </el-form-item> -->
            </el-form>
          </div>
          <!-- <div class="dianzanshuliang">
            <span class="video">下单数量</span>
            <el-input
              placeholder="请输入点赞数量(最低下单数100)"
              clearable
              autocomplete="off"
            ></el-input>
          </div> -->
          <div class="xuanzeshijian"></div>
          <div class="jine" style="margin-top: 120px">
            <div class="audio">
              订单总价:
              <!-- 单价乘以数量 -->
              <span
                class="ztys"
                v-if="item.need_text == false && item.need_time == false"
              >
                {{ (item.price * item.num).toFixed(2) | price }}
              </span>
              <!-- 单价乘以时间乘以数量 -->
              <span
                class="ztys"
                v-if="item.need_text == false && item.need_time == true"
              >
                {{ (item.price * item.num * item.time).toFixed(2) | price }}
              </span>
              <!-- 单价乘以评论长度 -->
              <span
                class="ztys"
                v-if="item.need_text == true && item.need_time == false"
              >
                {{ (item.price * item.textLength).toFixed(2) | price }}
              </span>
              <!-- 包时发言 -->
              <span
                class="ztys"
                v-if="
                  item.need_text == true &&
                  item.need_time == true &&
                  item.is_multiply == true
                "
              >
                {{ (item.price * item.time).toFixed(2) | price }}
              </span>
            </div>
            <div class="audio">
              我的余额:
              <span class="ztys">
                {{ userBalance.balance }}
              </span>
            </div>
          </div>
          <div class="anniu">
            <el-button
              type="danger"
              round
              class="queding"
              @click="confirmOrder(item.id, index)"
              >确定</el-button
            >
          </div>
          <div class="tixing">下单默认接受以上条款，如介意请勿下单！</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { _debounce1 } from "@/public/App";
import { mapState } from "vuex";
export default {
  props: {},
  data() {
    var checkNum = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("下单数量不能为空"));
      }
      const reg = /^[0-9]+$/;
      if (!reg.test(value)) {
        callback(new Error("请输入数字！"));
      } else {
        if (this.max_cnt) {
          value > this.max_cnt
            ? callback(new Error(`下单数量不能超过${this.max_cnt}！`))
            : value;
        }
        if (value < this.min_cnt) {
          callback(new Error(`下单数量不能低于${this.min_cnt}！`));
        } else {
          callback();
        }
        // if ((value*1)%(this.beishu*1)!=0){
        //   callback(new Error(`下单数量只能为${this.beishu}的倍数！`));
        // }else{
        //   callback();
        // }
      }
    };
    var checkText = (rule, value, callback) => {
      if (!value) callback(new Error("评论数量不能为空"));
      if (this.max_cnt) {
        this.tabList[this.textIndex].textLength > this.max_cnt
          ? callback(new Error(`评论数量不能超过${this.max_cnt}！`))
          : this.tabList[this.textIndex].textLength
      }
      if (this.tabList[this.textIndex].textLength < this.min_cnt) {
        callback(new Error(`评论数量不能低于${this.min_cnt}！`));
      } else {
        callback();
      }
    };
    return {
      max_cnt: '',
      min_cnt: '',
      listData: [],
      order_type: 3,
      tabNum: "1",
      type: "",
      voideList: [],
      streamingList: [],
      tabList: [],
      hunherenqi: [
        {
          value: "2"
        },
        {
          value: "3"
        },
        {
          value: "4"
        },
        {
          value: "5"
        },
        {
          value: "6"
        },
        {
          value: "8"
        },
        {
          value: "12"
        },
        {
          value: "20"
        }
      ],
      rules: {
        url: [
          { required: true, message: "请输入链接！", trigger: "blur" },
          {
            pattern: /(http|https):\/\/([\w.]+\/?)\S*/,
            message: "未输入链接！"
          }
        ],
        num: [
          { required: true, message: "请输入下单数量！", trigger: "blur" },
          { validator: checkNum, trigger: "blur" }
        ],
        time: [
          { required: true, message: "请选择订单时间！", trigger: "change" }
        ],
        text: [
          { validator: checkText, trigger: "blur" }
        ]
      },
      min_cnt: 0,
      max_cnt: "",
      isMobile: false,
      textIndex: 0,
      // beishu:1
    };
  },
  computed: {
    ...mapState(["userBalance"])
  },
  created() {
    this.KusinessList();
  },
  mounted() {
  },
  watch: {},
  methods: {
    minmaxText(item, index) {
      this.textIndex = index;
      this.min_cnt = item.min_cnt * 1;
      item.gaoshuliang
        ? (this.max_cnt = item.max_cnt * 1)
        : (this.max_cnt = "");
      this.textLength = 0;
      // item.beishu
      //   ? this.beishu = item.beishu
      //   : this.beishu = 1
    },
    zhibojiandancifayanshijian(e) {
      let textarea = [];
      textarea = e.split("\n").filter(item => {
        return item != "";
      });
      this.listData[this.textIndex].textLength = textarea.length;
      this.listData[this.textIndex].text = e;
    },
    minmaxNum(item) {
      // this.minNum = item.dishuliang * 1;
      this.min_cnt = item.min_cnt
      item.max_cnt
        ? (this.max_cnt = item.max_cnt * 1)
        : (this.max_cnt = "");
      this.textLength = 0;
      // item.beishu
      //   ? this.beishu = item.beishu
      //   : this.beishu = 1
    },
    //确定触发
    confirmOrder(formname, i) {
      this.$refs[formname][0].validate(valid => {
        if (valid) {
          let singleList = this.listData[i]
          let amount = 0
          let need_text = singleList.need_text
          let need_time = singleList.need_time
          let is_multiply = singleList.is_multiply
          //单价  评论
          if (need_text == true && need_time == false) {
            amount = singleList.textLength * singleList.price
          }
          //单价  数量
          if (need_text == false && need_time == false) {
            amount = singleList.price * singleList.num
          }
          //单价  时间  数量
          if (need_text == false && need_time == true) {
            amount = singleList.price * singleList.time * singleList.num
          }
          //包时发言
          if (need_text == true && need_time == true && is_multiply == true) {
            amount = singleList.price * singleList.time
          }
          if (this.userBalance.balance < amount) {
            this.$message({
              type: 'error',
              message: '下单失败,你的余额不足'
            })
            return;
          }
          this.$confirm('请确认地址是否正确,正确地址格式应为:https://v.kuaishou.com/******，每次只能对一个地址下单，如果地址有误将导致失败，请认真核对！?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.establishOrder(singleList, amount)
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消操作'
            })
          })
        }
      })
    },
    //创建订单接口
    async establishOrder(singleList, amount) {
      let data = {
        priceCfgId: singleList.id,                             //商品ID
        url_site: singleList.url,                              //url链接
        buyCnt: singleList.num,                                //购买数量
        pay_money: amount,                                     //应付金额
        comment_diy: singleList.text                           //评论内容
      }
      const [err, res] = await this.$http.request({
        url: '/createOrder',
        method: 'post',
        data
      })
      if (err) return
      console.log(res)
      if (res.data.result === 1) {
        this.$message({
          type: 'success',
          message: '下单成功'
        })
      }
    },
    // 快手业务接口
    async KusinessList() {
      let data = {
        order_type: this.order_type
      }
      const [err, res] = await this.$http.request({
        url: "/shopping",
        method: "GET",
        data
      });
      if (err) return;
      console.log(res.data.data)
      this.listData = res.data.data

    },
    handleClick: _debounce1(function (tab, e) {
      console.log(this.tabNum)
      if (this.tabNum === '1') {
        this.order_type = 3
        this.KusinessList()
      }
      if (this.tabNum === '2') {
        this.order_type = 4
        this.KusinessList()
      }
    }),
    selectItem(val) {
      this.type = val;
      switch (this.tabNum) {
        case "1":
          this.tabList = this.voideList.filter(item => {
            return item.ziduan == this.type;
          });
          break;
        case "2":
          this.tabList = this.streamingList.filter(item => {
            return item.ziduan == this.type;
          });
      }
    }
  },
  filters: {
    linkType(val) {
      return val == "0"
        ? "请输入您的主页链接（分享复制到此）"
        : "请输入您的视频链接（分享复制到此）";
    },
    price(val) {
      return val == "NaN" ? (0).toFixed(2) : val;
    }
  }
};
</script>

<style scoped lang="stylus">
@import './Kbusiness.styl';
</style>
